package cn.yunyichina.provider.bone.listener;

import cn.yunyichina.provider.bone.service.impl.BoneMsgServiceImpl;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.framework.dubbo.service.OrderService;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.bone.OrderBoneExtendVo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.XmlUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.ObjectArrayCodec;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.listener.MessageListener;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhuxp on 2017/10/27.
 *
 * @param
 * @Descrition
 */
@Log4j
public class BoneDiagnoseWechatPayMessageListener implements MessageListener<Integer, String> {

    @Override
    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
        String xmlString = integerStringConsumerRecord.value();
        log.info("骨科面诊订单回调, 入参xmlString = " + xmlString);
        try {
            Map<String, String> doc = XmlUtils.xmlToMap(xmlString);
            String orderNo = doc.get("out_trade_no");
            String openId = doc.get("openid");
            String appId = doc.get("appid");
            String attach = doc.get("attach");
            JSONObject jsonObj = JSONObject.parseObject(attach);
            String payMode = jsonObj.getString("pay_mode");
            String transactionId = doc.get("transaction_id");
            BigDecimal payAmount = new BigDecimal(doc.get("total_fee")).multiply(new BigDecimal(100));

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("order_no", orderNo);
            log.info("骨科面诊订单回调, 订单号" + orderNo + ", 调base模块, 查询订单信息入参request=" + JSONObject.toJSONString(dataMap));
            Response ordResponse = BaseService.callUnderlineFromInternal("", "yyt.base.order.by.order.no.out.get",
                    JsonUtils.toJsonString(dataMap));
            log.info("骨科面诊订单回调, 订单号" + orderNo + ", 调base模块, 查询订单信息返回response=" + JSONObject.toJSONString(ordResponse));
            if ("0".equals(ordResponse.getResultCode())) {
                OrderExtVo vo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
                vo.setPayTime(DateUtils.dateToString(new Date()));
                vo.setUpdateTime(DateUtils.dateToString(new Date()));
                // 101 已缴面诊费
                vo.setOrderStatus((short) 101);
                // 已支付
                vo.setPayStatusPayed();
                vo.setPayAppId(appId);
                vo.setPayMode(Short.parseShort(payMode));
                // 支付流水
                vo.setPaymentDealId(transactionId);
                log.info("骨科面诊回调, 订单号" + orderNo + ", 调base模块, 更新订单信息入参request=" + JSONObject.toJSONString(vo));
                BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(vo));
                sendMessages(vo);
            }else{
                log.info("骨科面诊单回调, 订单号" + orderNo + ", 调base模块, 查不到该订单.");
            }
        }catch (Exception e){
            log.error("骨科面诊订单回调异常", e);
        }

    }

    private void sendMessages(OrderExtVo vo) {

        final BoneMsgServiceImpl boneMsgService = SpringContextHandler.getBean("boneMsgServiceImpl");
        final String orderNo = vo.getOrderNo();
        final String patientName = vo.getUserName();
        final String scheduleTime =vo.getScheduleTime();
        final String reserveNo = vo.getReserveNo();
        final String address = vo.getUserAddress();
        final String userMobile = vo.getUserMobile();

        new Thread(new Runnable() {
            @Override
            public void run() {
                //发送微信给/患者
                boneMsgService.sendBoneMsgDiagnoseOrderToUser("{\"order_no\":\"" + orderNo + "\"}");
                //发送微信给/专家
                boneMsgService.sendBoneMsgDiagnoseOrderToDoctor("{\"order_no\":\"" + orderNo + "\"}");

                // 查询订单的拓展信息，是否有主治医生
                log.info("BoneDepositAlipayPayMessageListener骨科问诊/押金查询订单的拓展信息，是否有主治医生入参orderNo：" + orderNo);
                Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.get", "{\"order_no\":\"" + orderNo + "\"}");
                log.info("BoneDepositAlipayPayMessageListener骨科问诊/押金查询订单的拓展信息，是否有主治医生出参：" + JSON.toJSONString(orderRespone));
                OrderBoneExtendVo orderExtend = JsonUtils.parseObject(orderRespone.getResult(), OrderBoneExtendVo.class);
                String appointmentDoctorId = orderExtend.getAppointmentDoctorId();
                if (StringUtils.isNotBlank(appointmentDoctorId)) {
                    //查询专家信息
                    log.info("BoneDepositAlipayPayMessageListener查询专家的信息入参professorDoctorId：" + appointmentDoctorId);
                    Response professorResponse = BaseService.callHumpFromInternal(
                            "yyt.base.orguser.info.get", "{\"user_id\":\""
                                    + appointmentDoctorId + "\"}");
                    log.info("BoneDepositAlipayPayMessageListener查询专家的信息出参：" + professorResponse);
                    String professorResult = professorResponse.getResult();
                    if (StringUtils.isBlank(professorResult)) {
                        log.error("发送短信通知给医生异常，未查询到专家信息 userId: " + appointmentDoctorId);
                        return;
                    }
                    log.info("专家信息: " + professorResult);
                    JSONObject resultMap = JSON.parseObject(professorResult);
                    String mobile = resultMap.getString("mobile");
                    String doctorName = resultMap.getString("userName");

                    SimpleDateFormat simpleDateFormat  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String sdTime="";
                    try {
                      sdTime = simpleDateFormat.format(simpleDateFormat.parse(scheduleTime));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Map<String, Object> data = new HashMap<>();
                    data.put("to_user", userMobile);
                    data.put("msg_type", 96);
                    Map<String, String> msgContent = new HashMap<>();
                    msgContent.put("user_name", patientName);
                    msgContent.put("doctor_name", doctorName);
                    msgContent.put("schedule_time",sdTime);
                    msgContent.put("address",address);
                    msgContent.put("reserve_no",reserveNo);
                    data.put("msg_content", msgContent);

                    String dataJson = JSON.toJSONString(data);
                    // 发送短信给患者
                    log.info("发送短信给患者，参数: " + dataJson);
                    MessageService.callUnderlineFromInternal("yyt.message.msg.sms.send", dataJson);

                    Map<String,Object> userDate = new HashMap<>();
                    userDate.put("to_user", mobile);
                    userDate.put("msg_type", 97);
                    msgContent.remove("reserve_no");
                    userDate.put("msg_content", msgContent);
                    // 发送短信给医生
                    String jsonMap =  JSON.toJSONString(userDate);
                    log.info("发送短信给医生，参数: " + jsonMap);
                    MessageService.callUnderlineFromInternal("yyt.message.msg.sms.send", jsonMap);
                }

            }
        }).start();
    }

}
